package be.sc.classicnetwork.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import be.sc.classicnetwork.model.Request;
import be.sc.classicnetwork.service.GenericService;
import be.sc.classicnetwork.service.impl.EmailRequestTask;

public class RequestFormController extends AbstractFormController {

    private GenericService<Request> requestService;
    private String adminEmail;

    /**
     * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
     */
    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
	return new Request();
    }

    /**
     * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(java.lang.Object)
     */
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
	    BindException errors) throws Exception {
	Request req = (Request) command;

	// save the request
	this.requestService.saveOrUpdate(req);

	// send request by email to admin
	getTaskExecutor().execute(new EmailRequestTask(getServiceLocator().getMailService(), this.adminEmail));

	// show confirmation message
	return new ModelAndView("info", "text", "A representative of Classic Network will contact you very shortly");
    }

    public void setRequestService(GenericService<Request> requestService) {
	this.requestService = requestService;
    }

    public void setAdminEmail(String adminEmail) {
	this.adminEmail = adminEmail;
    }

}
